package control.interceptor;

import base.auth.JwtUtil;
import base.standard.constant.ErrorCode;
import base.standard.constant.ThreadLocalParams;
import base.standard.exception.SimpleException;
import base.util.AssertUtils;
import com.auth0.jwt.interfaces.Claim;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * Token interceptor
 *
 * @description: token 拦截器
 * @author: cyj
 * @date 2020 -10-21 20:39:46
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    @Qualifier("tokenCoreProcesses")
    private TokenProcesses tokenProcesses;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String token = Optional.ofNullable(request.getHeader("jwt-token")).orElseThrow(() ->
                new SimpleException(ErrorCode.ILLEGAL_ACCESS));
        Map<String, Claim> claims = JwtUtil.parseToken(token);
        String loginId = claims.get("loginId").asString();
        AssertUtils.check(StringUtils.isEmpty(loginId), ErrorCode.ILLEGAL_ACCESS);
        tokenProcesses.processes(loginId);
        request.setAttribute("loginId", loginId);
        ThreadLocalParams.setLoginId(loginId);
        return true;
    }
}
